package com.enzoism.springboot.dive.util;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestTemplateRetryUtil {

    private static final int MAX_RETRIES = 3;
    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发送 GET 请求并处理重试逻辑
     *
     * @param url          请求的 URL
     * @param responseType 响应的类型
     * @param <T>          响应类型的泛型
     * @return 响应实体
     */
    public static <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType) {
        return sendRequest(url, HttpMethod.GET, null, responseType);
    }

    /**
     * 发送 POST 请求并处理重试逻辑
     *
     * @param url          请求的 URL
     * @param requestBody  请求体
     * @param responseType 响应的类型
     * @param <T>          响应类型的泛型
     * @return 响应实体
     */
    public static <T> ResponseEntity<T> postForEntity(String url, Object requestBody, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers);
        return sendRequest(url, HttpMethod.POST, requestEntity, responseType);
    }

    /**
     * 发送请求并处理重试逻辑
     *
     * @param url           请求的 URL
     * @param method        请求方法
     * @param requestEntity 请求实体
     * @param responseType  响应的类型
     * @param <T>           响应类型的泛型
     * @return 响应实体
     */
    private static <T> ResponseEntity<T> sendRequest(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType) {
        int retries = 0;
        while (retries < MAX_RETRIES) {
            try {
                System.out.println("----------请求次数：" + retries + 1);
                ResponseEntity<T> response = restTemplate.exchange(url, method, requestEntity, responseType);
                if (response.getStatusCode().is2xxSuccessful()) {
                    return response;
                }
            } catch (Exception e) {
                // 发生异常时打印日志，可根据实际情况调整日志级别
                System.err.println("Request failed on attempt " + (retries + 1) + ": " + e.getMessage());
            }
            retries++;
        }
        // 重试 3 次后仍失败，返回 null
        return null;
    }

    public static void main(String[] args) {
        String url = "https://v1.hitokoto.cn222/?encode=json";
        // 示例：发送 GET 请求
        ResponseEntity<String> getResponse = getForEntity(url, String.class);
        if (getResponse != null && getResponse.getStatusCode().is2xxSuccessful()) {
            System.out.println("GET Response: " + getResponse.getBody());
        } else {
            System.out.println("GET request failed after retries.");
        }
    }
}